package online.zhangwenzhe.common;

import java.time.LocalDateTime;
import java.util.concurrent.atomic.AtomicLong;

public class NewID {
    //1806191724010001这个样子的号码

    long machineLeft = 10000;
    long minuteLeft = machineLeft * 100;
    long hourLeft = minuteLeft * 100;
    long dayLeft = hourLeft * 100;
    long monthLeft = dayLeft * 100;
    long yearLeft = monthLeft * 100;

    private long sequence;
    private int lastMinute = 0;
    private volatile static NewID singleton;

    private static NewID getInstance() {
        if (singleton == null) {
            synchronized (NewID.class) {
                if (singleton == null) {
                    singleton = new NewID();
                }
            }
        }
        return singleton;
    }

    public static long next() {
        return getInstance().getOne();
    }

    private synchronized long getOne() {
        LocalDateTime current = LocalDateTime.now();

        //每分钟计数清零
        if (lastMinute != current.getMinute()) {
            sequence = 0;
            lastMinute = current.getMinute();
        }

        sequence++;
        long prefix = (current.getYear() - 2000) * yearLeft +
                current.getMonthValue() * monthLeft +
                current.getDayOfMonth() * dayLeft +
                current.getHour() * hourLeft +
                current.getMinute() * minuteLeft +
                Environment.getMachineCode() * machineLeft;

        return prefix + sequence;
    }
}
